package com.dsteiner.xelavos.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import com.dsteiner.widgets.client.StringUtil;
import com.dsteiner.widgets.client.domain.ModelObject;
import com.dsteiner.xelavos.client.constants.Constants;
import com.dsteiner.xelavos.client.domain.HasImage;
import com.dsteiner.xelavos.client.domain.Product;
import com.dsteiner.xelavos.client.domain.User;
import com.dsteiner.xelavos.server.dao.DataDao;
import com.google.appengine.api.datastore.Blob;

public class FileUploadServlet extends HttpServlet {

	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		ServletFileUpload upload = new ServletFileUpload();
		upload.setSizeMax(10000000);
		res.setContentType("text/plain");
		PrintWriter out = res.getWriter();
		try {
			try {
				FileItemIterator iterator = upload.getItemIterator(req);
				while (iterator.hasNext()) {
					FileItemStream item = iterator.next();
					InputStream in = item.openStream();

					if (item.isFormField()) {
//						out.println("Got a form field: " + item.getFieldName());
					} else {
						String fieldName = item.getFieldName();
						String fileName = item.getName();
						String contentType = item.getContentType();

//						out.println("--------------");
//						out.println("fileName = " + fileName);
//						out.println("field name = " + fieldName);
//						out.println("contentType = " + contentType);

						try {
							Blob blob = new Blob(IOUtils.toByteArray(in));
							String imageId = DataDao.dataDao.saveFile(blob, req);
							String type = req.getParameter("type");
							String id = req.getParameter("id");
							if(!StringUtil.isEmpty(type) && !StringUtil.isEmpty(id)){
								Class<? extends ModelObject> forName = (Class<? extends ModelObject>) Class.forName(type);
								HasImage hasImage = (HasImage) DataDao.dataDao.getObjectById(id, forName);
								if(hasImage != null){
									hasImage.setImageId(imageId);
									DataDao.dataDao.updateObject((ModelObject) hasImage);
								}
							}
							out.print(imageId);
						} finally {
							IOUtils.closeQuietly(in);
						}

					}
				}
			} catch (SizeLimitExceededException e) {
				out.println("You exceeded the maximu size ("
						+ e.getPermittedSize() + ") of the file ("
						+ e.getActualSize() + ")");
			}
		} catch (Exception ex) {
			out.print(Constants.MSG_FILE_UPLOAD_FAILED);
			ex.printStackTrace();
		}
	}
}